package org.wisdom.s3.job.interceptor;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.wisdom.s3.job.feign.PeopleCenterTokenFeign;

import cn.hutool.json.JSONObject;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * fct请求拦截器
 *
 * @author 张智研
 * @date 2023/11/27 16:04
 */
@Slf4j
public class FctInterceptor implements RequestInterceptor {

    @Resource
    private PeopleCenterTokenFeign peopleCenterTokenFeign;

    @Value("${fct.source}")
    private String source;

    @Value("${fct.token}")
    private String token;

    private final ThreadLocal<String> accessTokenThreadLocal = new ThreadLocal<>();

    private final ThreadLocal<Long> dateTimeThreadLocal = new ThreadLocal<>();



    /**
     * 添加fct请求令牌
     *
     * @author 张智研
     * @date 2023/11/27 17:51
     * @param template 参数
     */
    @Override
    public void apply(RequestTemplate template) {
        // 获取token并加入到header中
        String accessToken;
        Long lastDateTime = this.dateTimeThreadLocal.get();
        Long dateTime = System.currentTimeMillis() - 30 * 60 * 1000;
        // 如果最后更新时间为空或者最后更新时间比当前时间早30分钟以上, 则重新获取token
        if (lastDateTime == null || dateTime.compareTo(lastDateTime) > 0) {
            dateTimeThreadLocal.remove();
            accessTokenThreadLocal.remove();
            // 请求people center令牌，并存放到线程缓存中
            log.info("获取fct令牌");
            JSONObject param = new JSONObject();
            param.set("source", this.source);
            param.set("token", this.token);
            JSONObject result = this.peopleCenterTokenFeign.getToken(param);
            if ("success".equalsIgnoreCase(result.getStr("code"))) {
                JSONObject data = result.getJSONObject("data");
                accessToken = data.getStr("access_token");
                this.accessTokenThreadLocal.set(accessToken);
                this.dateTimeThreadLocal.set(System.currentTimeMillis());
                log.info("向线程缓存中存入token【{}】", accessToken);
            } else {
                log.error("获取token令牌失败！！！");
                return;
            }
        }
        accessToken = this.accessTokenThreadLocal.get();
//        template.header("sysId", this.sysId);
        template.header("Authorization", accessToken);
    }
}
